package com.nhim.cms.dao;

// default package

import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.stereotype.Repository;

import com.nhim.cms.dao.IContentTypeElementDefinitionDAO;
import com.nhim.cms.domain.ContentTypeElementDefinition;
import com.nhim.core.dao.CoreDAO;

/**
 * A data access object (DAO) providing persistence and search support for
 * ContentTypeElementDefinition entities. Transaction control of the save(),
 * update() and delete() operations can directly support Spring
 * container-managed transactions or they can be augmented to handle
 * user-managed Spring transactions. Each of these methods provides additional
 * information for how to configure it for the desired type of transaction
 * control.
 * 
 * @see .ContentTypeElementDefinition
 * @author Huy Lieu TA
 */
@Repository("contentTypeElementDefinitionDAO")
public class ContentTypeElementDefinitionDAO extends
		CoreDAO<Integer, ContentTypeElementDefinition> implements
		IContentTypeElementDefinitionDAO {
	// property constants
	public static final String DESCRIPTION = "description";
	public static final String POSITION = "position";

	@Autowired
	EntityManagerFactory entityManagerFactory;

	@PostConstruct
	public void init() {
		super.setEntityManagerFactory(entityManagerFactory);
	}

	public static IContentTypeElementDefinitionDAO getFromApplicationContext(
			ApplicationContext ctx) {
		return (IContentTypeElementDefinitionDAO) ctx
				.getBean("contentTypeElementDefinitionDAO");
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<ContentTypeElementDefinition> findByProperty(
			String propertyName, final Object value) {
		logger.info("finding ContentTypeElementDefinition instance with property: "
				+ propertyName + ", value: " + value);
		try {
			final String queryString = "select model from ContentTypeElementDefinition model where model."
					+ propertyName + "= :propertyValue";
			return getJpaTemplate().executeFind(new JpaCallback<Object>() {
				public Object doInJpa(EntityManager em)
						throws PersistenceException {
					Query query = em.createQuery(queryString);
					query.setParameter("propertyValue", value);
					return query.getResultList();
				}
			});
		} catch (RuntimeException re) {
			logger.error("find by property name failed", re);
			throw re;
		}
	}
}